package com.wwcom.darteagle;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wwcom.darteagle.data.DartEagleDatabase;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.MatchLegs;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.MatchSets;
import com.wwcom.darteagle.model.Player;
import com.wwcom.darteagle.util.Settings;
import com.wwcom.darteagle.util.Settings.MatchSettings;


public class MatchSetupPlayersActivity extends Activity {
	
    private MatchPlayerArrayAdapter adapterPlayerList;
    private ListView playerList;    
	private final GlobalAppData gd= GlobalAppData.getSingletonInstance();

	private DartEagleDatabase db;
	
    /** Called when the activity is first created. */	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
	    //layout
        setContentView(R.layout.matchsetup_players);                        
        
    	//listeners 
        // handle "enter" keypress on new_player_name
        final EditText  newPlayer= (EditText)findViewById(R.id.new_player_name);
        EditText.OnKeyListener playerAddListener = new EditText.OnKeyListener(){
        	public boolean onKey(View v, int keyCode, KeyEvent event) {
    	        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
    	                (keyCode == KeyEvent.KEYCODE_ENTER)) {
    				   onClickPlayerAdd(newPlayer);
    				   return true;
    			   }
    			   return false;
    			}    	
    	};
    	newPlayer.setOnKeyListener(playerAddListener);
       	
    }
    
    
    @Override
    public void onResume() {
    	super.onResume();
    	if (db == null)
    		db= new DartEagleDatabase(this);   
    	
    	//check if we have a valid gd.matchInfo - if we don't we can't continue here
    	//we were likely removed from memory so deeply that the global data didn't survive
    	if (gd.matchInfo == null) {
    		finish();  //go back to front page
    		return;
    	}
    	//after this we are guarenteed to have a valid gd.matchInfo unless we are in onPause or later

        //autocomplete textview
    	List<Player> players= db.getPlayers();
    	List<String> playerNames= new ArrayList<String>(players.size());
    	for (Player p : players) {
    		playerNames.add(p.getName());
    	}
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, playerNames.toArray(new String[]{}));
        AutoCompleteTextView textView = (AutoCompleteTextView)
                findViewById(R.id.new_player_name);
        textView.setAdapter(adapter);
    	
        //players list
        adapterPlayerList = new MatchPlayerArrayAdapter(this, gd.matchInfo.getMatchPlayers());
        playerList= (ListView)findViewById(R.id.player_list);
        playerList.setAdapter(adapterPlayerList);

        //match description update
        ((TextView)findViewById(R.id.match_description)).setText(gd.matchInfo.getMatchDescription());    	
    }
            	        
    @Override
    public void onPause() {
    	super.onPause();
    	db.close();
    	db= null;    	
    }

    //buttons
    public void onClickPlayerAdd(View v) {
    	AutoCompleteTextView textView = (AutoCompleteTextView)
                findViewById(R.id.new_player_name);
    	String playerName= textView.getText().toString();
		if (playerName.equals("")) {
			Toast t = Toast.makeText(this, "Player names can not be empty, please choose another", Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
			t.show();
			return;
		}
    	
    	Player player= new Player(playerName);
    	
    	boolean found= false;
    	for (MatchPlayer mp : gd.matchInfo.getMatchPlayers()) {
    		Player p= mp.getPlayer();
    		if (p.getName().equals(player.getName())) {
    			found= true;
    			break;
    		}
    	}    	
		if (found) {
			Toast t = Toast.makeText(this, getString(R.string.matchsetup_unique_player_names), Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
			t.show();
			return;
		}
    	
		gd.matchInfo.addMatchPlayer(player);
		
    	adapterPlayerList.notifyDataSetChanged();
    	playerList.smoothScrollToPosition(playerList.getChildCount());
    	textView.setText("");
        ((TextView)findViewById(R.id.match_description)).setText(gd.matchInfo.getMatchDescription());
    }
    
	public void onClickPlayerRemove(View v) {
		Player player= (Player)v.getTag();
		gd.matchInfo.removeMatchPlayer(player);    	    	
    	adapterPlayerList.notifyDataSetChanged();
        ((TextView)findViewById(R.id.match_description)).setText(gd.matchInfo.getMatchDescription());
    }    
        
	public void onClickStartMatch(View v) {
		if (gd.matchInfo.getMatchPlayers().size() < 1) {
			Toast t = Toast.makeText(this, getString(R.string.matchsetup_add_one_player), Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
			t.show();
			return;
		}
		
		if (gd.matchInfo.getNumSets() > 0)
			gd.match= new MatchSets(gd.matchInfo);
		else
			gd.match= new MatchLegs(gd.matchInfo);
		
		gd.match.startPlaying(); 
		
		MatchSettings.updateSettings(gd.match);
		Settings.saveSettings(this);

		for (MatchPlayer mp : gd.match.getMatchPlayers()) {
			db.addPlayer(mp.getPlayer());
		}
				
		Intent i= new Intent(this,MatchActivity.class);
	    startActivity(i);
		finish();
	}

	public void onClickMatchSettings(View v) {
		finish();
		Intent i= new Intent(this,MatchSetupSettingsActivity.class);
	    startActivity(i);
	}

	//menus
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.darteagle_options_menu, menu);
        return true;
    }    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_options:
        	Intent i= new Intent(this,OptionsActivity.class);
        	startActivity(i);
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    // array adapters
	private class MatchPlayerArrayAdapter extends ArrayAdapter<MatchPlayer> {
    	private final List<MatchPlayer> list;
    	private final Context context;

    	public MatchPlayerArrayAdapter(Context context, List<MatchPlayer> list) {
    		super(context, R.layout.matchsetup_player_name_listview_row, list);
    		this.context = context;
    		this.list = list;
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View view = null;
    		if (convertView == null) {
    			LayoutInflater inflator = ((Activity) context).getLayoutInflater();
    			view = inflator.inflate(R.layout.matchsetup_player_name_listview_row, null);    			
    		} else {
    			view = convertView;
    		}
    		Player player= list.get(position).getPlayer();
    		((TextView)view.findViewById(R.id.player_name)).setText(player.getName());
    		((Button)view.findViewById(R.id.player_position)).setTag(player);
    		return view;
    	}
    	
    }
     
}